package com.cyzy.interceptor;

import com.cyzy.utils.TokenUtils;

import com.cyzy.utils.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;


/**
 * 过滤器
 */
@Configuration
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private TokenUtils tokenUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        System.out.println("token: " + token);
        if (token == null  || !redisTemplate.hasKey(token.replace("Bearer ", "")) ) {
            System.out.println("未提供认证令牌");
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "未提供认证令牌");
            return false;
        }
        try {

            boolean isValid = tokenUtils.validateToken(token.replace("Bearer ", ""));
//            System.out.println(token.replace("Bearer ", "") + "------------");
            System.out.println(isValid);
            if (!isValid) {
                response.setHeader("Context-Type", "text/html;charset=utf-8");
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "无效令牌");
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "令牌验证失败");
            return false;
        }
//        String s = redisTemplate.opsForValue().get(token.replace("Bearer ", ""));
//        System.out.println(s);
        UserContext.setUserId(redisTemplate.opsForValue().get(token.replace("Bearer ", "")));
        return true;
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        UserContext.clear(); // 请求结束后清理 ThreadLocal，防止内存泄漏
    }










}
